package cn.tedu.fruitshop.service.impl;

import cn.tedu.fruitshop.ex.ServiceException;
import cn.tedu.fruitshop.mapper.OrdersMapper;
import cn.tedu.fruitshop.pojo.dto.ItemUpdateInfoDTO;
import cn.tedu.fruitshop.pojo.dto.OrderAddCarDTO;
import cn.tedu.fruitshop.pojo.dto.OrdersAddNewDTO;
import cn.tedu.fruitshop.pojo.dto.OrdersUpdateInfoDTO;
import cn.tedu.fruitshop.pojo.entity.Orders;
import cn.tedu.fruitshop.pojo.vo.CarDetailsVO;
import cn.tedu.fruitshop.pojo.vo.ItemStandardVO;
import cn.tedu.fruitshop.pojo.vo.OrdersListItemVO;
import cn.tedu.fruitshop.pojo.vo.OrdersStandardVO;
import cn.tedu.fruitshop.service.IOrdersService;
import cn.tedu.fruitshop.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import sun.awt.windows.ThemeReader;

import javax.validation.constraints.NotNull;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class OrdersServiceImpl implements IOrdersService {
    @Autowired
    OrdersMapper ordersMapper;

    @Autowired
    CarServiceImpl carService;

    @Autowired
    ItemServiceImpl itemService;

    @Override
    public void addNew(OrdersAddNewDTO ordersAddNewDTO) {
        log.debug("开始处理【添加订单】的业务，参数：{}", ordersAddNewDTO);
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersAddNewDTO, order);
        log.debug("即将插入订单数据：{}", order);
        int rows = ordersMapper.insert(order);
        if (rows != 1) {
            String message = "服务器炸了,添加数据失败";
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("插入订单数据完成");
    }

    @Override
    public void delete(Integer id) {
        log.debug("开始处理【删除订单】的业务，参数：{}", id);
        OrdersStandardVO queryResult = ordersMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "删除订单失败,尝试访问的数据不存在";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        int rows = ordersMapper.deleteById(id);
        if (rows != 1) {
            String message = "服务器炸了,删除数据失败";
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public List<OrdersListItemVO> list() {
        return ordersMapper.list();
    }

    @Override
    public void updateInfoById(Integer id, OrdersUpdateInfoDTO ordersUpdateInfoDTO) {
        log.debug("开始处理【修改订单详情】的业务，参数ID：{}, 新数据：{}", id, ordersUpdateInfoDTO);
        OrdersStandardVO queryResult = ordersMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "修改订单详情失败！尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersUpdateInfoDTO, orders);
        log.debug("即将修改数据：{}", orders);
        int rows = ordersMapper.update(orders);
        if (rows != 1) {
            String message = "修改订单详情失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public List<OrdersStandardVO> getByUserId(Long id) {
        log.debug("开始处理【根据id查询订单列表】的业务，参数：{}", id);
        List<OrdersStandardVO> orders = ordersMapper.getByUserId(id);
        if (orders == null || orders.size() == 0) {
            String message = "获取订单列表失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        log.debug("查询订单的数据为:{}",orders);
        return orders;
    }

    @Override
    public void addOrder(OrderAddCarDTO orderAddCarDTO) {
        log.info("开始添加订单：{}", orderAddCarDTO);
        Integer userId = orderAddCarDTO.getUserId();
        List<CarDetailsVO> list = carService.list(userId);
        for (CarDetailsVO carDetailsVO : list) {
            ItemStandardVO standardById = itemService.getStandardById(carDetailsVO.getItemId());
            ItemUpdateInfoDTO itemUpdateInfoDTO = new ItemUpdateInfoDTO();
            itemUpdateInfoDTO.setSaleCount(standardById.getSaleCount()+1);
            if ((standardById.getNum()- carDetailsVO.getWeight()) < 0.0 ){
                String message = "商品【" + standardById.getName() +"】库存只剩:【" + standardById.getNum() + "】购买失败！";
                throw new ServiceException(ServiceCode.ERR_INSERT, message);
            }
            itemUpdateInfoDTO.setNum((standardById.getNum()- carDetailsVO.getWeight()));
            itemService.updateInfoById(carDetailsVO.getItemId(),itemUpdateInfoDTO);
        }
        Orders orders = new Orders();
        BeanUtils.copyProperties(orderAddCarDTO, orders);
        orders.setTotal(orderAddCarDTO.getTotalPrice());
        orders.setOrderNum(1);
        Integer count = carService.getCount(orderAddCarDTO.getUserId());
        orders.setNum(count);
        orders.setPayTime(LocalDateTime.now());
        orders.setSendTime(LocalDateTime.now());
        orders.setShipAddress("太原");
        orders.setState("正在发货请等待...");
        ordersMapper.insert(orders);
        log.info("添加订单完成：{}",orders);
        log.info("删除购物车，{}", orderAddCarDTO.getUserId());
        carService.deleteByUesrId(orderAddCarDTO.getUserId());
    }

}
